import { resolve } from 'path'
import { ConfigEnv, defineConfig, PluginOption, UserConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import fs from 'fs'
import dts from 'vite-plugin-dts'
import viteClean from 'vite-plugin-clean'
import { visualizer } from 'rollup-plugin-visualizer'
import terser from '@rollup/plugin-terser'
import { PreRenderedAsset } from 'rollup'
import Components from 'unplugin-vue-components/vite'
/** 按需加载注册组件，引用构建后的组件，不方便修改调试，本项目使用全局注册组件方式 */
// import { EpDesignerCoreResolver } from 'ep-designer-core/es/utils/EpDesignerCoreResolver'

type ComponentCategory = 'pc' | 'mobile'

// 该函数用于扫描指定目录下的组件，并生成相应的入口文件路径
function getComponentEntries(category: ComponentCategory): Record<string, string> {
  const componentDir = category === 'pc' ? 'components' : 'mobile-components'
  const baseDir = resolve(__dirname, `package/${componentDir}`)
  const entries: Record<string, string> = {}

  // 扫描组件目录
  if (fs.existsSync(baseDir)) {
    fs.readdirSync(baseDir).forEach((name) => {
      const entryPath = resolve(resolve(baseDir, name), 'index.ts')

      if (fs.existsSync(entryPath)) {
        // 生成带分类标识的入口键名
        entries[`${componentDir}/${name}/index`] = entryPath
      }
    })
  }
  return entries
}

function getAssetFileNames(chunkInfo: PreRenderedAsset): string {
  if (chunkInfo.name === 'ep-designer-core.css') {
    return 'index.css'
  }
  return chunkInfo.name as string
}

// https://vitejs.dev/config/
export default defineConfig(({ mode }: ConfigEnv): UserConfig => {
  const isUMDBuild = mode === 'umd'
  return {
    base: '',
    resolve: {
      alias: {
        '~': resolve(__dirname, 'package'),
        '@': resolve(__dirname, 'src'),
        'ep-designer-core/es': resolve(__dirname, 'es')
      }
    },
    build: {
      cssCodeSplit: !isUMDBuild, // 是否将 CSS 代码拆分成单独的文件
      sourcemap: false, // 是否生成 source map 文件
      emptyOutDir: true, // 是否在构建前清空输出目录
      lib: {
        entry: isUMDBuild
          ? resolve(__dirname, 'package/full.ts') // UMD 构建入口
          : {
              // 全量安装入口
              index: resolve(__dirname, 'package/index.ts'),
              // PC 端入口
              pc: resolve(__dirname, 'package/pc.ts'),
              'components/index': resolve(__dirname, 'package/components/index.ts'),
              // 移动端入口
              mobile: resolve(__dirname, 'package/mobile.ts'),
              'mobile-components/index': resolve(__dirname, 'package/mobile-components/index.ts'),
              // 工具函数入口
              'utils/withInstall': resolve(__dirname, 'package/utils/withInstall.ts'),
              'utils/EpDesignerCoreResolver': resolve(__dirname, 'package/utils/EpDesignerCoreResolver.ts'),
              // 自动扫描生成的入口
              ...getComponentEntries('pc'),
              ...getComponentEntries('mobile')
            },
        name: 'ep-designer-core' // 库名称
        // formats: isUMDBuild ? ['umd'] : ['es', 'cjs'] // 这里不需要设置 formats，rollup 会根据 output 的配置自动处理
      },
      rollupOptions: {
        // 确保外部化处理那些你不想打包进库的依赖
        external: [
          'vue',
          'element-plus',
          'vant',
          'tailwindcss',
          'ace-builds',
          'lodash',
          'axios',
          'moment',
          'compressorjs',
          'sortablejs'
        ],
        // 入口文件的输出配置
        output: isUMDBuild
          ? [
              {
                format: 'umd',
                entryFileNames: 'index.full.js', // 非压缩版本
                dir: './dist',
                name: 'ep-designer-core',
                globals: {
                  vue: 'Vue',
                  'element-plus': 'ElementPlus',
                  vant: 'vant'
                },
                assetFileNames: getAssetFileNames
              },
              {
                format: 'umd',
                entryFileNames: 'index.full.min.js', // 压缩版本
                dir: './dist',
                name: 'ep-designer-core',
                globals: {
                  vue: 'Vue',
                  'element-plus': 'ElementPlus',
                  vant: 'vant'
                },
                plugins: [
                  terser() as PluginOption // 使用 @rollup/plugin-terser 压缩
                ],
                assetFileNames: getAssetFileNames
              }
            ]
          : [
              {
                format: 'es',
                entryFileNames: '[name].mjs',
                dir: './es',
                preserveModules: true,
                preserveModulesRoot: 'package',
                exports: 'named',
                assetFileNames: getAssetFileNames
              },
              {
                format: 'cjs',
                entryFileNames: '[name].cjs',
                dir: './lib',
                preserveModules: true,
                preserveModulesRoot: 'package',
                exports: 'named',
                assetFileNames: getAssetFileNames
              }
            ]
      },
      minify: isUMDBuild ? false : 'terser', // 是否压缩代码
      reportCompressedSize: false,
      chunkSizeWarningLimit: 800, // 规定触发警告的 chunk 大小。（以 kbs 为单位）
      terserOptions: {
        compress: {
          drop_console: false,
          drop_debugger: true
        }
      }
    },
    css: {
      preprocessorOptions: {
        scss: { api: 'modern-compiler' }
      }
    },
    plugins: [
      vue(),
      viteClean({
        targetFiles: ['dist/**/*', 'lib/**/*', 'es/**/*']
      }),
      dts({
        tsconfigPath: './tsconfig.lib.json',
        insertTypesEntry: true, // 是否在 package.json 中插入 types 字段
        staticImport: true, // 是否使用静态导入
        outDir: 'lib'
      }),
      dts({
        tsconfigPath: './tsconfig.lib.json',
        insertTypesEntry: true, // 是否在 package.json 中插入 types 字段
        staticImport: true, // 是否使用静态导入
        outDir: 'es'
      }),
      // vite-plugin-components 组件自动导入
      Components({
        resolvers: [
          // EpDesignerCoreResolver()
        ]
      }),
      visualizer() as PluginOption
    ]
  }
})
